package com.wsjzzcbq.qianyuan.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * FileUtils
 *
 * @author wsjz
 * @date 2022/03/14
 */
@Slf4j
public class FileUtils {

    /**
     * 获取文件类型
     * @param file
     * @return
     */
    public static String getFileType(String file) {
        return file.substring(file.lastIndexOf("."));
    }

    /**
     * 图片转base64字符串
     * @param fileAddr
     * @return
     */
    public static String image2Base64(String fileAddr) {
        if (StringUtils.isBlank(fileAddr)) {
            throw new NullPointerException("image2Base64 fileAddr id not null or ''");
        }
        File file = new File(fileAddr);

        try(FileInputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            return Base64.encodeBase64String(baos.toByteArray());
        } catch (Exception e) {
            log.error("image2Base64 fileAddr", e);
            return null;
        }
    }
}
